<!--
 * Tencent is pleased to support the open source community by making Tars available.
 *
 * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
 *
 * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * https://opensource.org/licenses/BSD-3-Clause
 *
 * Unless required by applicable law or agreed to in writing, software distributed
 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" href="../css/bootstrap.min.css">
    <link rel="stylesheet" href="../css/bootstrap_table.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <!--[if lt IE 9]>
    <script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <script src="../js/jquery.min.js"></script>
    <script src="../js/bootstrap.min.js"></script>
    <script src="../js/bootstrap_table.min.js"></script>
    <script src="../js/template.js"></script>
    <script src="../js/common.js"></script>
</head>
<body>
<h4 id="main_title">服务扩容</h4>
<form class="form-horizontal" role="form">
    <div class="form-group">
        <div class="col-sm-1"><label for="app-name" class="control-label wp100">应用 <span class="text-danger">*</span></label></div>
        <div class="col-sm-2">
            <select name="application" id="app-name" class="form-control"><option>请选择</option></select>
        </div>
        <div class="col-sm-1"><label class="control-label wp100">服务 <span class="text-danger">*</span></label></div>
        <div class="col-sm-2">
            <select name="server_name" id="server-name" class="form-control"><option>请选择</option></select>
        </div>
        <div class="col-sm-1"><label class="control-label wp100">Set <span class="text-danger">*</span></label></div>
        <div class="col-sm-2">
            <select name="set_name" id="set" class="form-control"><option>请选择</option></select>
        </div>
        <div class="col-sm-1"><label class="control-label wp100">节点 <span class="text-danger">*</span></label></div>
        <div class="col-sm-2">
            <select name="node_name" id="node-name" class="form-control"><option>请选择</option></select>
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-1"><label for="server-name" class="control-label wp100">目标IP <span class="text-danger">*</span></label></div>
        <div class="col-sm-4" id="tar-ip-box">
            <textarea class="form-control" id="tar-ip" rows="3" placeholder="可输入多个IP，以以逗号（,）、分号（;）或换行（\n）分隔"></textarea>
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-1"><label for="server-name" class="control-label wp100">Set分组 <span class="text-danger">*</span></label></div>
        <div class="col-sm-4" style="margin-left: -15px;">
            <div class="col-sm-3"><label class="checkbox-inline"> <input type="checkbox" id="enable-set" name="enable_set"> 启用Set</label></div>
            <div class="col-sm-3"><input type="text" class="form-control" placeholder="Set名,全英文小写" title="Set名,全英文小写" name="set_name" id="set-name" disabled></div>
            <div class="col-sm-3"><input type="text" class="form-control" placeholder="Set地区,全英文小写" title="Set地区,全英文小写" name="set_area" id="set-area" disabled></div>
            <div class="col-sm-3"><input type="text" class="form-control" placeholder="Set组名,数字或*号" title="Set组名,数字或*号" name="set_group" id="set-group" disabled></div>
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-1"><label class="control-label wp100">节点配置 <span class="text-danger">*</span></label></div>
        <div class="col-sm-10">
            <label class="checkbox-inline"> <input type="checkbox" id="enable-node-copy" name="enable_node_copy"> 复制节点配置</label>
        </div>
    </div>
    <div class="tc mb10">
        <button type="button" class="btn btn-primary" id="btn-submit">预扩容</button>
    </div>
</form>

<div id="table-box"></div>


<div id="msg" style="display: none"></div>



<script type="text/html" id="tpl">
    <table class="table table-hover table-bordered" id="obj-table">
        <thead>
        <tr>
            <th><label><input type="checkbox" class="check-all" onchange="checkAll(this)"></label></th>
            <th>应用</th>
            <th>服务</th>
            <th>Set</th>
            <th>OBJ名称</th>
            <th>节点</th>
            <th>绑定IP</th>
            <th>端口</th>
            <th>模板名</th>
            <th>状态</th>
        </tr>
        </thead>
        <tbody>
        {{each data as it}}
        <tr>
            <td>
                {{if it.status=='未扩容'}}
                <label><input type="checkbox" class="chks" data-node-name="{{it.node_name}}" data-set="{{it.set}}" data-obj-name="{{it.obj_name}}"></label>
                {{/if}}
            </td>
            <td>{{it.application}}</td>
            <td>{{it.server_name}}</td>
            <td>{{it.set}}</td>
            <td>{{it.obj_name}}</td>
            <td>{{it.node_name}}</td>
            <td><input type="text" value="{{it.bind_ip}}" class="bind-ip-value form-control"></td>
            <td><input type="text" value="{{it.port}}" class="port-value form-control w80"></td>
            <td>{{it.template_name}}</td>
            <td>{{it.status}}</td>
        </tr>
        {{/each}}
        </tbody>
    </table>
    <div class="tc"><button type="button" id="expand-btn" class="btn btn-primary">扩容</button></div>
</script>



<script>
    var gData = {};

    gData.$appName = $('#app-name');
    gData.$serverName = $('#server-name');
    gData.$set = $('#set');
    gData.$nodeName = $('#node-name');
    gData.regIp = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;

    getcascadeData({},function (data) {
        var htmlStr = '<option value=""></option>';
        $.each(data,function (i,n) {
            htmlStr += '<option value="'+n+'">'+n+'</option>';
        });
        gData.$appName.html(htmlStr);
    });

    gData.$appName.change(function () {
        if(!$(this).val()) return;
        getcascadeData({level:2,application:$(this).val()},function (data) {
            var htmlStr = '<option value=""></option>';
            $.each(data,function (i,n) {
                htmlStr += '<option value="'+n+'">'+n+'</option>';
            });
            gData.$serverName.html(htmlStr);
        });
    });

    gData.$serverName.change(function () {
        if(!$(this).val()) return;
        getcascadeData({level:3,application:gData.$appName.val(),server_name:$(this).val()},function (data) {
            var htmlStr = '<option value=""></option>';
            $.each(data,function (i,n) {
                if(!n){
                    htmlStr += '<option value="">不启用Set</option>';
                }else{
                    htmlStr += '<option value="'+n+'">'+n+'</option>';
                }
            });
            gData.$set.html(htmlStr);
        });
    });

    gData.$set.change(function () {
        getcascadeData({level:4,application:gData.$appName.val(),server_name:gData.$serverName.val(),set_name:$(this).val()},function (data) {
            var htmlStr = '';
            $.each(data,function (i,n) {
                htmlStr += '<option value="'+n+'">'+n+'</option>';
            });
            gData.$nodeName.html(htmlStr);
        });
    });

    $('#enable-set').change(function () {
        if(this.checked){
            $(this).parents('.col-sm-4').find('.form-control').removeAttr('disabled');
        }else{
            $(this).parents('.col-sm-4').find('.form-control').attr('disabled','disabled');
        }
    });


    $('#tar-ip').on('blur',function () {
        var ips = $(this).val(),a,n=0;
        if(ips){
            a = ips.split(/[,;\n]/);
            for(var i=0;i<a.length;i++){
                if(!gData.regIp.test(a[i])){
                    $(this).parent().addClass('has-error');
                    return;
                }else{
                    n++;
                }
            }
            if(n==a.length){
                $(this).parent().removeClass('has-error');
            }
        }
    });

    $('#btn-submit').click(function () {
        var paramObj = {
            application     :   $('#app-name').val(),
            server_name     :   $('#server-name').val(),
            set             :   $('#set').val(),
            node_name       :   $.trim($('#node-name').val()),
            set_name        :   $.trim($('#set-name').val()),
            set_area        :   $.trim($('#set-area').val()),
            set_group       :   $.trim($('#set-group').val()),
            expand_nodes    :   $('#tar-ip').val(),
            enable_set      :   $('#enable-set')[0].checked ? true : false,
            copy_node_config:   $('#enable-node-copy')[0].checked ? true : false
        };
        closeErrorMsg();
        if(!paramObj.application){
            showErrorMsg($('body'),'应用名不能为空');
            return;
        }
        if(!paramObj.server_name){
            showErrorMsg($('body'),'服务名不能为空');
            return;
        }
        if(!paramObj.node_name){
            showErrorMsg($('body'),'节点不能为空');
            return;
        }
        if(!paramObj.expand_nodes){
            showErrorMsg($('body'),'目标IP不能为空');
            return;
        }
        paramObj.expand_nodes = paramObj.expand_nodes.split(/[,;\n]/);
        if(paramObj.enable_set){
            if(!paramObj.set_name){
                showErrorMsg($('body'),'Set名不能为空');
                return;
            }
            if(!paramObj.set_area){
                showErrorMsg($('body'),'Set区域不能为空');
                return;
            }
            if(!paramObj.set_group){
                showErrorMsg($('body'),'Set组名不能为空');
                return;
            }
            if(!/^[a-z]+$/.test(paramObj.set_name)){
                showErrorMsg($('body'),'Set名只能为英文字母，且必须小写');
                return;
            }
            if(!/^[a-z]+$/.test(paramObj.set_area)){
                showErrorMsg($('body'),'Set区域只能为英文字母，且必须小写');
                return;
            }
            if(!/^([a-z]+|\d+|\*)$/.test(paramObj.set_group)){
                showErrorMsg($('body'),'Set组必须为数字或*号或者英文小写字母');
                return;
            }
        }else{
            delete paramObj.set_area;
            delete paramObj.set_name;
            delete paramObj.set_group;
        }

        var param = $.stringify(paramObj);
        gData.expandInfo = {
            application     :   paramObj.application,
            server_name     :   paramObj.server_name,
            set             :   paramObj.set,
            node_name       :   paramObj.node_name,
            copy_node_config:   paramObj.copy_node_config
        };
        showLoading();
        $.ajax('/pages/server/api/expand_server_preview',{
            contentType:'application/json',
            method:'post',
            data:param,
            dataType:'json',
            success:function (data) {
                removeLoading();
                var $msg = $('#msg');
                if(data.ret_code==200){
                    //$msg.html('<div class="alert alert-success" role="alert"><h5>预扩容成功！</h5><p>点击确定后，绑定IP和端口进行扩容</p></div>');
                    var htmlStr = template('tpl',data);
                    $('#table-box').html(htmlStr);
                }else{
                    $msg.html('<div class="alert alert-danger" role="alert">预扩容失败！请联系管理员</div>');
                    showDialog($msg,'信息提示');
                }
            }
        });
    });

    $('#table-box').on('blur','.bind-ip-value',function () {
        if(!gData.regIp.test($(this).val())){
            $(this).parent().addClass('has-error');
        }else{
            $(this).parent().removeClass('has-error');
        }
    });
    $('#table-box').on('keyup','.port-value',function (e) {
        if(!(e.keyCode>47 && e.keyCode<59) && !(e.keyCode>95 && e.keyCode<106) && e.keyCode!=8 && e.keyCode!=46){
            return false;
        }
    });

    $('#table-box').on('click','#expand-btn',function () {
        closeErrorMsg();
        var tmp = [],o={},
            $chks = $('.chks:checked');
        if(!$chks.length){
            showErrorMsg($('body'),'请先勾选要扩容的对象');
            return;
        }
        if($('.has-error').length){
            showErrorMsg($('body'),'请正确填写IP地址');
            return;
        }
        $('.chks:checked').each(function () {
            o = {
                node_name   :   $(this).data('node-name'),
                set         :   $(this).data('set'),
                obj_name    :   $(this).data('obj-name'),
                bind_ip     :   $(this).parents('tr').find('.bind-ip-value').val(),
                port        :   $(this).parents('tr').find('.port-value').val()
            };
            tmp.push(o);
        });
        var paramObj = {
            application           : gData.expandInfo.application,
            server_name           : gData.expandInfo.server_name,
            set                   : gData.expandInfo.set,
            node_name             : gData.expandInfo.node_name,
            copy_node_config      : gData.expandInfo.copy_node_config,
            expand_preview_servers: tmp
        };
        showLoading();
        var param = $.stringify(paramObj);
        $.ajax('/pages/server/api/expand_server',{
            contentType:'application/json',
            method:'post',
            data:param,
            dataType:'json',
            success:function (data) {
                removeLoading();
                var $msg = $('#msg');
                if(data.ret_code==200){
                    $msg.html('<div class="alert alert-success" role="alert"><h5>扩容成功！</h5></div>');
                }else{
                    $msg.html('<div class="alert alert-danger" role="alert">扩容失败！请联系管理员</div>');
                }
                showDialog($msg,'信息提示');
            }
        });
    });
    
    function getcascadeData(params,callback) {
        params = params || {};
        var paramObj = {
            level       : params.level || 1,
            application : params.application || '',
            server_name : params.server_name || '',
            set         : params.set_name || ''
        };
        $.each(paramObj,function (i,n) {
            if(!n){
                delete paramObj[i];
            }
        });
        var param = $.param(paramObj);
        $.getJSON('/pages/server/api/cascade_select_server?'+param,function (data) {
            if(data.ret_code==200){
                if($.isFunction(callback)){
                    callback(data.data);
                }
            }else{
                //TODO 目前没啥好做的
            }
        });
    }


</script>
</body>
</html>
